#!/usr/bin/env node

/**
 * NPM 包安装后的配置脚本
 * 自动设置环境变量和创建全局命令
 */

const { execSync } = require('child_process');
const { platform, homedir } = require('os');
const { join } = require('path');
const { writeFileSync, existsSync } = require('fs');
const readline = require('readline');

const colors = {
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m',
  reset: '\x1b[0m'
};

function log(message, color = 'white') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

async function askQuestion(question) {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  return new Promise((resolve) => {
    rl.question(`${colors.cyan}${question}${colors.reset}`, (answer) => {
      rl.close();
      resolve(answer.trim());
    });
  });
}

async function main() {
  console.log('');
  log('🐕 大狗AI助手安装完成！', 'yellow');
  console.log('');

  // 检查是否已有API密钥
  if (process.env.DEEPSEEK_API_KEY) {
    log('✅ 检测到 DEEPSEEK_API_KEY 环境变量', 'green');
    log('🎉 你现在可以直接使用 dagou 命令了！', 'green');
    console.log('');
    log('示例用法:', 'cyan');
    log('  dagou -p "你好，介绍一下自己"', 'blue');
    log('  dagou --help', 'blue');
    return;
  }

  log('🔑 需要配置 DeepSeek API 密钥', 'yellow');
  log('📝 获取地址: https://platform.deepseek.com/api_keys', 'blue');
  console.log('');

  const shouldConfigure = await askQuestion('是否现在配置 API 密钥？(y/n): ');
  
  if (shouldConfigure.toLowerCase() !== 'y') {
    console.log('');
    log('⚠️  你可以稍后手动设置环境变量:', 'yellow');
    
    if (platform() === 'win32') {
      log('  setx DEEPSEEK_API_KEY "你的API密钥"', 'cyan');
    } else {
      log('  export DEEPSEEK_API_KEY="你的API密钥"', 'cyan');
      log('  echo \'export DEEPSEEK_API_KEY="你的API密钥"\' >> ~/.bashrc', 'cyan');
    }
    return;
  }

  const apiKey = await askQuestion('请输入你的 DeepSeek API 密钥 (以 sk- 开头): ');
  
  if (!apiKey || !apiKey.startsWith('sk-')) {
    log('❌ API 密钥格式不正确，应该以 sk- 开头', 'red');
    return;
  }

  // 设置环境变量
  if (platform() === 'win32') {
    try {
      execSync(`setx DEEPSEEK_API_KEY "${apiKey}"`, { stdio: 'inherit' });
      log('✅ 环境变量已设置 (Windows)', 'green');
    } catch (error) {
      log('❌ 设置环境变量失败', 'red');
    }
  } else {
    const shell = process.env.SHELL || '/bin/bash';
    const rcFile = shell.includes('zsh') ? '.zshrc' : '.bashrc';
    const rcPath = join(homedir(), rcFile);
    
    try {
      const exportLine = `export DEEPSEEK_API_KEY="${apiKey}"`;
      writeFileSync(rcPath, `\n${exportLine}\n`, { flag: 'a' });
      log(`✅ 环境变量已添加到 ${rcFile}`, 'green');
      log('💡 请重启终端或运行 source ~/' + rcFile, 'blue');
    } catch (error) {
      log('❌ 设置环境变量失败', 'red');
    }
  }

  console.log('');
  log('🎉 配置完成！现在你可以使用 dagou 命令了！', 'green');
  console.log('');
  log('示例用法:', 'cyan');
  log('  dagou -p "你好，介绍一下自己"', 'blue');
  log('  dagou -m deepseek-coder -p "写一个Python程序"', 'blue');
  log('  dagou --help', 'blue');
}

// 只在非CI环境中运行交互式配置
if (!process.env.CI && !process.env.npm_config_yes) {
  main().catch(() => {
    // 忽略错误，允许静默安装
  });
}